package com.llb666.java;

/**
 * 单例模式
 * @author 斌~
 * @version 1.0
 * @date 2021/4/12 上午3:11
 */
public class TestSingleton {
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance == instance1); //true
    }
}

class Singleton{
    /**构造函数私有化**/
    private Singleton(){}
    /**volatile 修饰保证线程可见，避免指令重排**/
    private static volatile Singleton singleton = null;
    /**
     * 对外提供获取实例对象的方法
     */
    public static Singleton getInstance(){
        //只有null才创建对象
        if(singleton == null){
            //保证线程安全
            synchronized (Singleton.class){
                if(singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}
